package com.chem.lems.serves.impl;

import com.chem.lems.constans.EquipStateCinstant;
import com.chem.lems.constans.ResultCodeConstant;
import com.chem.lems.entity.Equipment;
import com.chem.lems.entity.Record;
import com.chem.lems.entity.Role;
import com.chem.lems.entity.User;
import com.chem.lems.repository.EquipmentRepository;
import com.chem.lems.repository.RecordRepository;
import com.chem.lems.repository.RoleRepository;
import com.chem.lems.repository.UserRepository;
import com.chem.lems.serves.RecordServies;
import com.chem.lems.utils.ECharts;
import com.chem.lems.utils.EChartsUtil;
import com.chem.lems.utils.ResultUtil;
import com.chem.lems.vo.EquipProVO;
import com.chem.lems.vo.UserRepVO;
import com.chem.lems.vo.YearVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.ObjectName;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class RecordServiesImpl implements RecordServies {
    @Autowired
    private RecordRepository recordRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private EquipmentRepository equipmentRepository;

    /**
     * 查询全部记录
     *
     * @return
     */
    @Override
    public ResultUtil gitRecordList() {
        List<Record> recordList = recordRepository.findAll();
        return new ResultUtil(ResultCodeConstant.SUCCESS, "查询成功！", recordList);
    }

    /**
     * 用户角色统计
     *
     * @return
     */
    public ResultUtil gituserRecord() {
        Map<String, ECharts> map = new HashMap();
        List valueList = new ArrayList();
        List<Role> roleRepositoryAll = roleRepository.findAll();
        for (Role role : roleRepositoryAll) {
            List<User> userRepositoryAll = userRepository.findStudents(role.getRoleId());
            ECharts data = filtrUserInfo(role.getRoleDesc(), userRepositoryAll);
            if (null != data) {
                map.put(role.getRoleDesc(), data);
            }
        }
        List<ECharts> result = new ArrayList(map.values());
        return new ResultUtil(ResultCodeConstant.SUCCESS, "查询成功！", result);
    }

    /**
     * 用户统计属性过滤封装
     *
     * @param roleName
     * @param userRepositoryAll
     * @return
     */
    public ECharts filtrUserInfo(String roleName, List<User> userRepositoryAll) {
        Integer nmb = 0;
        Integer male = 0;
        Integer female = 0;
        String value = null;
        if (null != userRepositoryAll && !userRepositoryAll.isEmpty()) {
            nmb = userRepositoryAll.size();
            for (User user : userRepositoryAll) {
                if ("男".equals(user.getSex())) {
                    male++;
                } else {
                    female++;
                }
            }
            NumberFormat numberFormat = NumberFormat.getInstance();
            String maleRate = numberFormat.format((float) male / (float) nmb * 100).concat("%");
            String femaleRate = numberFormat.format((float) female / (float) nmb * 100).concat("%");
            return EChartsUtil.delECharts(String.valueOf(nmb), roleName, String.valueOf(male), String.valueOf(female), maleRate, femaleRate);
        }
        return null;
    }


    /**
     * 用户数量统计
     *
     * @return
     */
    public ResultUtil gituserNumbRecord() {
        Integer total = userRepository.findAll().size();
        Integer online = userRepository.findAllOnline().size();
        Map<String, String> dayMap = getFirstAndLastDays();
        String firstday = dayMap.get("firstday");
        String lastday = dayMap.get("lastday");
        Integer add = userRepository.findAllAddUser(firstday, lastday).size();
        Integer login = userRepository.findAllLoginUser(firstday, lastday).size();
        UserRepVO userRepVO = new UserRepVO(total, online, add, login);
        return new ResultUtil(ResultCodeConstant.SUCCESS, "查询成功！", userRepVO);
    }

    public Map<String, String> getFirstAndLastDays() {
        Calendar cale = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String firstday, lastday;
        cale.add(Calendar.MONTH, 0);
        cale.set(Calendar.DAY_OF_MONTH, 1);
        firstday = format.format(cale.getTime());
        cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        lastday = format.format(cale.getTime());
        Map<String, String> map = new HashMap<>();
        map.put("firstday", firstday);
        map.put("lastday", lastday);
        return map;
    }

    /**
     * 设备增加统计
     *
     * @return
     */
    public ResultUtil gitEquipAddRecord() {
        List<Date> equipmentRepositoryAll = equipmentRepository.findAllDateObj();
        YearVO yearVO = new YearVO();
        if (null != equipmentRepositoryAll && !equipmentRepositoryAll.isEmpty()) {
            Map<String, Integer> map = new HashMap<>();
            Calendar calender = Calendar.getInstance();
            Integer nowYear = calender.get(Calendar.YEAR);
            for (Date date : equipmentRepositoryAll) {
                calender.setTime(date);
                Integer yaer = calender.get(Calendar.YEAR);
                if (nowYear.equals(yaer)) {
                    Integer march = calender.get(Calendar.MARCH) + 1;
                    yearVO.addMarch(march);
                }
            }
        }
        List list = new ArrayList();
        list.add(yearVO.getJanuary());
        list.add(yearVO.getFebruary());
        list.add(yearVO.getMarch());
        list.add(yearVO.getApril());
        list.add(yearVO.getMay());
        list.add(yearVO.getJune());
        list.add(yearVO.getJuly());
        list.add(yearVO.getAugust());
        list.add(yearVO.getSeptember());
        list.add(yearVO.getOctober());
        list.add(yearVO.getNovember());
        list.add(yearVO.getDecember());
        return new ResultUtil(ResultCodeConstant.SUCCESS, "查询成功！", list);
    }

    /**
     * 设备使用统计
     *
     * @return
     */
    public ResultUtil gitEquipUseRecord() {
        Integer total = equipmentRepository.findAll().size();
        if (total == 0) {
            return new ResultUtil(ResultCodeConstant.FAIL, "查询失败！");
        }
        Integer idleInt = equipmentRepository.findAllByState(EquipStateCinstant.IDLE.code()).size();
        Integer damageInt = equipmentRepository.findAllByState(EquipStateCinstant.DAMAGRED.code()).size();
        Integer repairInt = equipmentRepository.findAllByState(EquipStateCinstant.MAINTENANCE.code()).size();
        Integer userInt = total - idleInt - damageInt - repairInt;
        EquipProVO equipPro = new EquipProVO();
        NumberFormat numberFormat = NumberFormat.getInstance();
        float idle = (float) idleInt / (float) total * 100;
        float damage = (float) damageInt / (float) total * 100;
        float repair = (float) repairInt / (float) total * 100;
        float user = (float) userInt / (float) total * 100;
        equipPro.setTotal(total);
        equipPro.setIdle(new BigDecimal(idle).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
        equipPro.setDamage(new BigDecimal(damage).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
        equipPro.setRepair(new BigDecimal(repair).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
        equipPro.setUse(new BigDecimal(user).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
        return new ResultUtil(ResultCodeConstant.SUCCESS, "查询成功！", equipPro);
    }

    /**
     * 获取用户的设备历史借用的记录
     *
     * @return
     */
    @Override
    public ResultUtil gitRecordListByUserId(String userId) {
        List<Record> result = recordRepository.findAllByUserId(userId);
        if (result.isEmpty()) {
            return new ResultUtil(ResultCodeConstant.FAIL, "设备历史借用记录获取失败！");
        }
        return new ResultUtil(ResultCodeConstant.SUCCESS, "设备历史借用记录获取成功！", result);
    }
}
